#include "FunctionModeParser.h"

#include "QStringParser.h"
#include "IntParser.h"
#include "ModeParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

FunctionModeParser::FunctionModeParser(
    ModeParser *&_modeParser
    , IntParser *&_levelParser
    , QStringParser *&_commentParser
):    m_modeParser(_modeParser)
    , m_levelParser(_levelParser)
    , m_commentParser(_commentParser)
{

}

bool FunctionModeParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new FunctionMode());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("mode")))
    {
        data = reader->attributes().value(QStringLiteral("mode"));
        if (!m_modeParser->parse(reader, data))
            return false;
        m_result->mode = m_modeParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("mode: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("level")))
    {
        data = reader->attributes().value(QStringLiteral("level"));
        if (!m_levelParser->parse(reader, data))
            return false;
        m_result->level = m_levelParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("level: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("comment")))
    {
        data = reader->attributes().value(QStringLiteral("comment"));
        if (!m_commentParser->parse(reader, data))
            return false;
        m_result->commentOptional = Optional<QString>(m_commentParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

FunctionMode *FunctionModeParser::result()
{
    return m_result.take();
}

}